<!--
	作者：2575202388@qq.com
	时间：2018-10-16
	描述：下拉组件
-->
<template>
	<div style="position: relative;z-index: 1000;width: 100%;">
		<div ref="nav" style="min-height:20px;width: 100%;">
			<slot name="nav"></slot>
		</div>
		<div ref="box" class="box">
			<div v-if="border" style="height: 1px;background: #e5e5e5;"></div>
			<div ref="targget">
				<slot name="content"></slot>
			</div>
		</div>
	</div>

</template>

<script>
	export default {
		name: "Dropdown",
		props: {
			border: {
				type: Boolean,
				default: true
			},
			speed: {
				type: String,
				default: "50"
			}
		},
		data() {
			return {
				timer: null,
				status: false
			}
		},
		methods: {
			toggle() {
				this.animate(!this.status);
			},
			open() {
				this.animate(true);
			},
			close() {
				this.animate(false);
			},
			animate(status) {

				this.status = status
				const box = this.$refs.box;
				box.style.top = this.$refs.offsetHeight;
				if(box) {
					if(this.timer) {
						clearInterval(this.timer);
					}
					this.timer = setInterval(() => {
						let targgetH = this.getElementHeight();
						if(this.status && box.offsetHeight >= targgetH) {
							clearInterval(this.timer);
						} else if(!this.status && box.offsetHeight <= 0) {
							clearInterval(this.timer);
						} else {
							var height = box.offsetHeight + this.genaraSpeed();
							if(this.status && height > targgetH) {
								height = targgetH;
							}
							if(!this.status && height < 0) {
								height = 0;
							}
							box.style.height = height + 'px';
						}
					}, 1);

				}
			},
			genaraSpeed() {
				var tempH = Math.ceil(this.getElementHeight() / this.getSpeed());
				if(!this.status) {
					tempH = -tempH;
				}
				return tempH;
			},
			getSpeed() { //动画速度
				return Number(this.speed);
			},
			getElementHeight() { //滑动高度
				let targget = this.$refs.targget;
				var height = 0;
				if(this.border == true) {
					height = targget.offsetHeight + 1;
				} else {
					height = targget.offsetHeight;
				}
				return height;
			}

		}
	}
</script>

<style scoped="scoped">
	.box {
		overflow-y: hidden;
		height: 0px;
		position: absolute;
		background: #FFFFFF;
		width: 100%;
	}
</style>